﻿using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.SM;
using System.Collections.Generic;
using UFIDA.U9.ISV.SM;
using UFIDA.U9.SPR.SalePriceList;
using UFSoft.UBF.Util.DataAccess;

namespace dz.inner.jky.api.service
{
    internal class SalePriceListService : BaseService
    {
        public U9CResult Add(DzSalePriceListDTO dto)
        {
            return util.U9Invoke(__Add, dto,dto.Org);
        }

        private U9CResult __Add(DzSalePriceListDTO dto)
        {
            U9CResult result = new U9CResult();

            CommonCreateSalePriceListSRV sv = new CommonCreateSalePriceListSRV();

            sv.SalePricelistDtos = Convert(dto);

            var rtn = sv.Do();

            result.DocNo = (rtn[0].ID>0) ? SalePriceList.Finder.FindByID(rtn[0].ID).Code : string.Empty ;
            result.Id = rtn[0].ID;
            result.IsSuccess = true;

            UpdatePriceList(result);

            return result;
        }

        private void UpdatePriceList(U9CResult result)
        {
            SalePriceList entity = SalePriceList.Finder.FindByID(result.Id);

            string sql = $@"update CBO_Customer set PriceListID = {result.Id},PriceListCode = '{result.DocNo}',PriceListName = '{result.DocNo}' 
                        where id = {entity.SalePriceLines[0].Customer.ID}";


            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null);
        }
        private List<SalePriceListDTO> Convert(DzSalePriceListDTO ori)
        {
            SalePriceListDTO dto = new SalePriceListDTO();

            ObjectCopyUtil util = new ObjectCopyUtil();

            util.CopyProperty(ori, ref dto);


            List<SalePriceListDTO> rtn = new List<SalePriceListDTO>() { dto };

            return rtn;
        }
    }
}
